package com.sky.aspect;

import com.sky.annotation.AutoFill;
import com.sky.constant.AutoFillConstant;
import com.sky.context.BaseContext;
import com.sky.enumeration.OperationType;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.time.LocalDateTime;
import java.time.LocalTime;

@Aspect
@Component
@Slf4j
public class AutoFillAspect {

    @Pointcut("execution(* com.sky.mapper.*.*(..)) && @annotation(com.sky.annotation.AutoFill)" )
    public void autoFillPointCut(){}

    @Before("autoFillPointCut()")
    public void autoFill(JoinPoint joinPoint) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        //获取数据库操作类型
        log.info("进入了切片");
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        AutoFill autoFill = methodSignature.getMethod().getAnnotation(AutoFill.class);
        OperationType operationType =  autoFill.value();

        //获取实体
        Object[] os =  joinPoint.getArgs();
        if(os.length == 0){return;}
        Object o = os[0];

        //准备赋值数据
        LocalDateTime now = LocalDateTime.now();
        Long currentId = BaseContext.getCurrentId();

        //反射赋值
        if(operationType == OperationType.INSERT){
            Method setUpdateTime =  o.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME,LocalDateTime.class);
            Method setCreateTime =  o.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_TIME,LocalDateTime.class);
            Method setUpdateUser =  o.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER,Long.class);
            Method setCreateUser =  o.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_USER,Long.class);

            setCreateTime.invoke(o,now);
            setUpdateTime.invoke(o,now);
            setCreateUser.invoke(o,currentId);
            setUpdateUser.invoke(o,currentId);

            log.info("++++++++++++++++当前  o is {}",o.toString());

        }else if(operationType == OperationType.UPDATE){
            Method setUpdateTime =  o.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME,LocalDateTime.class);
            Method setUpdateUser =  o.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER,Long.class);
            setUpdateUser.invoke(o,currentId);
            setUpdateTime.invoke(o,now);
        }
    }
}
